// import Authorized from '@/utils/Authorized';
import React, { PureComponent, Fragment } from 'react';
import {
  Avatar,
  Card,
  Table,
  Button,
  Form,
  Modal,
  Input,
  Divider,
  Tag,
  Checkbox,
  Upload,
  Icon,
  Row,
  Col,
  Select
} from 'antd';
import { connect } from 'dva';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from "./Admin.less";

const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const { Option } = Select;

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

/**
 * 新增或编辑用户组件, 根据传值与否控制
 */
@connect(({ authRole, loading }) => ({
  authRole,
  loading: loading.models.authRole,
}))
@Form.create()
class AddOrUpdateForm extends PureComponent {

  state = {
    uploadLoading: false,
  }

  componentWillReceiveProps(nextProps) {
    const { values } = nextProps;
    this.setState({
      imageUrl: values.avatar
    })
  }

  okHandle = () => {
    const { form, handleAdd, handleUpdate, values } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (fieldsValue.avatar) {
        fieldsValue.avatar = fieldsValue.avatar.file.response.data.path;
      }
      if (values && Object.keys(values).length) {
        handleUpdate(fieldsValue)
      } else {
        handleAdd(fieldsValue);
      }
    });
  }

  /**
   * 上传图片
   */
  handleUpload = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ uploadLoading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl => this.setState({
        imageUrl,
        uploadLoading: false,
      }));
    }
  }

  /**
   * 验证下方密码
   */
  validateToNextPassword = (rule, value, callback) => {
    const { confirmDirty } = this.state;
    const { form } = this.props;
    if (value && confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  }

  /**
   * 确认密码改变
   */
  handleConfirmBlur = (e) => {
    const { confirmDirty } = this.state;
    const { value } = e.target;
    this.setState({ confirmDirty: confirmDirty || !!value });
  }

  /**
   * 比对原密码
   */
  compareToFirstPassword = (rule, value, callback) => {
    const { form } = this.props;
    if (value && value !== form.getFieldValue('password')) {
      callback('确认密码不匹配!');
    } else {
      callback();
    }
  }

  render() {
    const { uploadLoading, imageUrl } = this.state;
    const { authRole: { list }, modalVisible, form, handleModalVisible, values } = this.props;
    const uploadButton = (
      <div>
        <Icon type={uploadLoading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <Modal
        destroyOnClose
        title={values && Object.keys(values).length ? "编辑用户" : "新增用户"}
        visible={modalVisible}
        onOk={this.okHandle}
        onCancel={() => handleModalVisible(false)}
      >
        <Form>
          <div>
            {form.getFieldDecorator('uid', {
              initialValue: values && Object.keys(values).length ? values.uid : null
            })(
              <Input type="hidden" />
            )}
          </div>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="用户名">
            {form.getFieldDecorator('userName', {
              initialValue: values && Object.keys(values).length ? values.userName : null,
              rules: [{ required: true, message: '用户名必填！' }],
            })(
              <Input disabled={Object.keys(values).length > 0} />
            )}
          </FormItem>
          {!Object.keys(values).length ? (
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="密码">
              {form.getFieldDecorator('password', {
                rules: [
                  { required: true, message: '密码必填！' },
                  { validator: this.validateToNextPassword, }
                ],
              })(
                <Input type="password" />
              )}
            </FormItem>
          ) : null}
          {!Object.keys(values).length ? (
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="确认密码">
              {form.getFieldDecorator('confirm', {
                rules: [
                  { required: true, message: '确认密码必填！' },
                  { validator: this.compareToFirstPassword }],
              })(
                <Input type="password" onBlur={this.handleConfirmBlur} />
              )}
            </FormItem>
          ) : null}
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="手机">
            {form.getFieldDecorator('phone', {
              initialValue: values && Object.keys(values).length ? values.phone : null
            })(
              <Input />
            )}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="邮箱">
            {form.getFieldDecorator('email', {
              initialValue: values && Object.keys(values).length ? values.email : null
            })(
              <Input />
            )}
          </FormItem>
          <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="头像">
            {form.getFieldDecorator('avatar', {

            })(
              <Upload
                name="file"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="/back/upload"
                onChange={this.handleUpload}
              >
                {imageUrl ? <img className={styles.avatar} src={imageUrl} alt="avatar" /> : uploadButton}
              </Upload>
            )}
          </FormItem>
          {
            Object.keys(list).length ?
              (
                <FormItem
                  labelCol={{ span: 5 }}
                  wrapperCol={{ span: 15 }}
                  label="角色"
                >
                  {form.getFieldDecorator('roleIds', {
                    initialValue: values && Object.keys(values).length ? values.roles.map(role => role.roleId) : null,
                    rules: [{ required: true, message: '角色必选！' }],
                  })(
                    <CheckboxGroup options={list.map(role => ({ label: role.roleDesc, value: role.roleId }))} />
                  )}
                </FormItem>
              ) : null
          }
        </Form>
      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ authAdmin, authRole, loading }) => ({
  authAdmin,
  authRole,
  loading: loading.models.authAdmin,
}))
@Form.create()
class UserList extends PureComponent {
  state = {
    modalVisible: false,
    selectedRowKeys: [],
    stepFormValues: {},
  };

  columns = [
    {
      title: '用户名',
      dataIndex: 'userName'
    },
    {
      title: '角色',
      dataIndex: 'roles',
      render: val => val.map(role => <Tag key={role.roleId} color="blue">{role.roleDesc}</Tag>)
    },
    {
      title: '头像',
      dataIndex: 'avatar',
      render: val => {
        if (val) {
          if (val.indexOf('http://') === -1 && val.indexOf('https://') === -1) {
            return <Avatar size="small" src={'/back/' + val} />;
          }
          return <Avatar size="small" src={val} />;
        }
        return <Avatar size="small" icon="user" />;
      }
    },
    {
      title: '手机',
      dataIndex: 'phone',
      render: val => {
        return val ? val : '-'
      }
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      render: val => {
        return val ? val : '-'
      }
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate'
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified'
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, record)}>编辑</a>
          <Divider type="vertical" />
          <a onClick={() => this.handleDel(record)}>删除</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch, authAdmin: { data } } = this.props;
    this.pageData(data.size, data.current)

    dispatch({
      type: 'authRole/list',
    });
  }

  /**
   * 表格多选
   */
  handleSelectRows = selectedRowKeys => {
    console.log(selectedRowKeys)
    this.setState({
      selectedRowKeys,
    });
  };

  /**
   * 控制编辑模态
   */
  handleModalVisible = (flag, record) => {
    this.setState({
      modalVisible: !!flag,
      stepFormValues: record || {},
    });
  };

  /**
   * 新增
   */
  handleAdd = fields => {
    const { dispatch } = this.props;
    console.log(fields)
    dispatch({
      type: 'authAdmin/add',
      payload: {
        ...fields
      },
    })
    this.handleModalVisible();
  };

  /**
   * 更新
   */
  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'authAdmin/update',
      payload: {
        ...fields
      },
    })
    this.handleModalVisible();
  };

  /**
   * 批量删除
   */
  handleDelBatch = (selectedRowKeys) => {
    const that = this;
    Modal.confirm({
      title: `确定删除选中的 ${selectedRowKeys.length} 项 ?`,
      okText: "确认",
      cancelText: "取消",
      onOk() {
        that.props.dispatch({
          type: 'authAdmin/delBatch',
          payload: selectedRowKeys
        })
      },
      onCancel() { },
    });
  }

  /**
   * 删除
   */
  handleDel = (record) => {
    const that = this;
    Modal.confirm({
      title: `确定删除此项 ?`,
      okText: "确认",
      cancelText: "取消",
      onOk() {
        that.props.dispatch({
          type: 'authAdmin/del',
          payload: {
            uid: record.uid
          }
        })
      },
      onCancel() { },
    });
  }

  /**
   * 表单查询
   */
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form, authAdmin: { data } } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'authAdmin/updateSearch',
        payload: {
          ...fieldsValue
        }
      })
      this.pageData(data.size, 1, ...fieldsValue)
    });
  };

  /**
   * 表单重置
   */
  handleFormReset = () => {
    const { authAdmin: { data }, form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'authAdmin/updateSearch',
      payload: {}
    })
    this.pageData(data.size, 1)
  };

  /**
   * 切换显示
   * @param {*} current 
   */
  changePage(current) {
    const { authAdmin: { data, searchValues } } = this.props;
    this.pageData(data.size, current, searchValues)
  }

  /**
   * 切换显示数量
   * @param {*} pageSize 
   * @param {*} current 
   */
  changePageSize(pageSize, current) {
    const { authAdmin: { searchValues } } = this.props;
    this.pageData(pageSize, current, searchValues)
  }

  pageData(pageSize, pageIndex, searchValues) {
    const { dispatch } = this.props;
    dispatch({
      type: 'authAdmin/page',
      payload: {
        pageIndex,
        pageSize,
        searchValues
      }
    })
  }

  renderForm() {
    const {
      form: { getFieldDecorator }, authRole: { list }
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="用户名">
              {getFieldDecorator('userName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="角色">
              {getFieldDecorator('roleId')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  {
                    list.map(i => (
                      <Option key="roleId" value={i.roleId}>{i.roleDesc}</Option>
                    ))
                  }
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { loading, authAdmin: { data } } = this.props;

    const {
      selectedRowKeys,
      modalVisible,
      stepFormValues,
    } = this.state;

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleSelectRows
    };

    // 分页配置
    const pagination = {
      showSizeChanger: true,
      showQuickJumper: false,
      showTotal: () => `共${data.total}条`,
      pageSize: data.size,
      current: data.current,
      total: data.total,
      records: data.total,
      onShowSizeChange: (currentPage, newPageSize) => this.changePageSize(newPageSize, currentPage),
      onChange: (currentPage) => this.changePage(currentPage),
    };

    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      handleUpdate: this.handleUpdate,
      handleAdd: this.handleAdd,
    };

    return (
      <PageHeaderWrapper title="管理员管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              {/* <Authorized authority="admin"> */}
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>新建</Button>
              {/* </Authorized> */}
              {selectedRowKeys.length > 0 && (
                <span>
                  <Button icon="delete" onClick={() => this.handleDelBatch(selectedRowKeys)}>删除</Button>
                </span>
              )}
            </div>
            <Table
              rowSelection={rowSelection}
              loading={loading}
              dataSource={data.records}
              columns={this.columns}
              rowKey="uid"
              pagination={pagination}
            />
          </div>
        </Card>
        <AddOrUpdateForm
          {...parentMethods}
          modalVisible={modalVisible}
          values={stepFormValues}
        />
      </PageHeaderWrapper>
    )
  }
}

export default UserList;